import { getListApi, getByTypeApi, getByNameApi, getByIdApi, getByHotApi, getByTimeApi } from "../../api";

const actions = {
  // 获取商品列表信息
  getList(context, value) {
    getListApi(
      (response) => {
        context.commit("GETLIST", { data: response.data.data || [], maxPage: response.data.maxPage || 1 });
      },
      (err) => {
        console.log(err);
      },
      value
    );
  },

  // 通过商品分类 id 获取 商品列表信息
  getByType(context, value) {
    getByTypeApi(
      (response) => {
        context.commit("GETLIST", { data: response.data.data || [], maxPage: response.data.maxPage || 1 });
      },
      (err) => {
        console.log(err);
      },
      value
    );
  },

  // 通过商品名称获取 商品列表
  getByName(context, value) {
    getByNameApi(
      (response) => {
        context.commit("GETLIST", { data: response.data.data || [], maxPage: response.data.maxPage || 1 });
      },
      (err) => {
        console.log(err);
      },
      value
    );
  },

  // 通过商品id 获取商品详情
  getById(context, value) {
    getByIdApi(
      (response) => {
        context.commit("GETLIST", { data: response.data.data || [], maxPage: response.data.maxPage || 1 });
      },
      (err) => {
        console.log(err);
      },
      value
    )
  },

  // 获取 热销 产品
  getByHot(context) {
    getByHotApi(
      (response) => {
        context.commit("GETLIST", { data: response.data.data || [], maxPage: response.data.maxPage || 1 });
      },
      (err) => {
        console.log(err);
      }
    );
  },


  // 获取热销推荐
  getHotRec(context) {
    getByHotApi(
      (response) => {
        if (response.data.data.length > 4) {
          response.data.data = response.data.data.slice(0, 4);
        }
        context.commit("GETHOTREC", response.data.data || []);
      },
      (err) => {
        console.log(err);
      }
    );
  },

  // 获取新品
  getByTime(context) {
    getByTimeApi(
      (response) => {
        context.commit("GETLIST", { data: response.data.data || [], maxPage: response.data.maxPage || 1 });
      },
      (err) => {
        console.log(err);
      }
    );
  },

  // 获取新品推荐
  getNewRec(context) {
    getByTimeApi(
      (response) => {
        if (response.data.data.length > 4) {
          response.data.data = response.data.data.slice(0, 4);
        }
        context.commit("GETNEWREC", response.data.data || []);
      },
      (err) => {
        console.log(err);
      }
    );
  },
}

const mutations = {
  GETLIST(state, value) {
    state.goodsList = value.data;
    state.maxPage = value.maxPage;
  },
  DELETE(state) {
    state.goodsList = [];
  },
  GETHOTREC(state, value) {
    state.hotRecommend = value;
  },
  GETNEWREC(state, value) {
    state.newRecommend = value;
  },
}

const getters = {

}

const state = {
  // 总共页数
  maxPage: 1,
  // 商品列表
  goodsList: [],
  // 热销商品
  hotRecommend: [],
  // 新品
  newRecommend: [],
}

export default {
  namespaced: true,
  actions,
  mutations,
  getters,
  state,
}